<template>
    <div id="map">
        <el-button-group style="position:absolute;z-index:100;left: 250px;top:20px">
            <el-button id="chang" type="primary" icon="el-icon-search" @click="measuredistance">长度</el-button>
            <el-button type="primary" icon="el-icon-share" @click="measurearea">面积</el-button>
            <el-button type="primary" icon="el-icon-delete" @click="measurecancel">取消</el-button>
        </el-button-group>
        <el-row style="position:absolute;z-index:100;left: 500px;top:20px">
            <el-button type="primary" @click="print">打印地图</el-button>

        </el-row>
        <div style="position: absolute;width: 100px;right: 50px;top:50px;z-index:100;background-color: #F2F6FC;border-radius: 4px">
            <el-checkbox v-model="checked1" style="margin-left: 15px" >底图点</el-checkbox>
            <el-checkbox v-model="checked2" >底图线</el-checkbox>
            <el-checkbox v-model="checked3"> 底图面</el-checkbox>
            <el-checkbox v-model="checked4">沉降点</el-checkbox>
            <el-checkbox v-model="checked5">水平点</el-checkbox>
        </div>

        <el-dialog
            title="监测数据曲线图"
            :visible.sync="dialogVisible"

            :fullscreen="isfullscreen"
            :before-close="handleClose"
            top="1vh"
        >
            <div id="echarts1" style="height: 400px;width: 900px;"> </div>
            <div id="echarts2" style="height: 400px;width: 900px;"> </div>
            <span slot="footer" class="dialog-footer">
            </span>
        </el-dialog>

    </div>
</template>

<script>

    ////第三方
    import $ from 'jquery'
    import echarts from 'echarts'

    ////地图
    import 'ol/ol.css'
    //地图图层
    import { Map, View } from 'ol'
    import Tile from 'ol/layer/Tile'
    import XYZ from 'ol/source/XYZ'
    import {Tile as TileLayer, Vector as VectorLayer} from 'ol/layer';
    import {TileJSON, Vector as VectorSource} from 'ol/source';
    //图形
    import Feature from 'ol/Feature'
    import Polygon from 'ol/geom/Polygon'
    import Point from'ol/geom/Point'
    import LineString from 'ol/geom/LineString'
    import MultiLineString from 'ol/geom/MultiLineString';
    import Circle from 'ol/geom/Circle';
    //样式
    import {Fill, Icon, Stroke, Style,RegularShape,Circle as CircleStyle ,Text} from 'ol/style'
    //交互
    import Draw from 'ol/interaction/Draw'
    import Overlay from 'ol/Overlay';
    import {addProjection, addCoordinateTransforms, transform} from 'ol/proj'
    import {getArea} from "ol/sphere"
    import Select from 'ol/interaction/Select';
    ////自定义
    import Popup from "../components/popup"
    import '../style/popup.css'
    export default {
        /**************************************************************数据*********************************************************************/
        data(){
            return {
                checkList: ['1','2','3','4','5'],
                checked1:true,
                checked2:true,
                checked3:true,
                checked4:true,
                checked5:true,
                name:"地图",
                map:null,
                baselayerpoint:null,
                baselayerpolyline:null,
                baselayerpolygon:null,
                jsonlayer1:null,
                jsonlayer2:null,
                //测量
                measureSource:null,
                mmeasureVectorlayer:null,
                measureTooltipElement:null,
                measureOverlay:null,
                selectSingleClick:null,
                urlpath:'./static/json/',

                dialogVisible: false,
                option1:null,
                option2:null,
                isfullscreen:true


            }
        },
        /**************************************************************组件*********************************************************************/
        components: {

        },
        created()
        {
            self = this;
            window.showDlg= self.showDlg;
        },
        /**************************************************************mounted*********************************************************************/
        mounted(){
            this.$http.get(this.urlpath+'东坝12.geojson')
                .then(function(response)
                {
                    console.log(response);
                })
                .catch(function (error) { // 请求失败处理
                    console.log(error);
                });
            var view=new View({
                //center:ol.proj.transform([110,39],"EPSG:4326","EPSG:3857"),
                //center:[-1131808,605000],
                //zoom:7,
                //extent:[-1246647,456556,-1017802,722617]
            });
            var map=new Map({
                layers: [
                    /*            getTdtLayer("vec_w"),
                                getTdtLayer("cva_w")*/
                ],
                view:view,

                target: 'map'
            });
            this.map=map;

            view.fit([-1423386,452201,-756179,750305]);
            view.setZoom(9)
            /*添加底图图层*/
            this.addBaselayers(this.urlpath+"东坝底图");
            /*添加自定义图层*/
            var that=this;
            //添加第一个自定义图层
            var url1=this.urlpath+"东坝12.geojson";
            $.ajax({
                type: "GET",
                url: url1,
                dataType:'json',
                //data: {id:1001},//也可以是字符串链接"id=1001"，建议用对象
                success: function(data){
                    //create featuresource and featurelayer
                    var jsonSource=new VectorSource({
                    });
                    var features=data.features;
                    for (var i=0;i<features.length;i++)
                    {
                        var feature=features[i];
                        var newfeature=new Feature({
                            geometry:new Point(feature.geometry.coordinates)
                        });
                        newfeature.set("layer",feature.properties.Layer);
                        newfeature.set("text",feature.properties.Text);
                        newfeature.set("vl",i);
                        /*                var a=newfeature.getProperties();
                                        console.log(a);*/
                        jsonSource.addFeature(newfeature);
                    }
                    that.jsonlayer1=new VectorLayer({
                        source:jsonSource,
                        enderMode:'image',
                        style: function (feature) {
                            return styleFunction(feature,3)
                        }
                    });
                    that.map.addLayer(that.jsonlayer1);
                }
            });
            //添加第二个自定义图层
            var url2=this.urlpath+"东坝42.geojson";
            $.ajax({
                type: "GET",
                url: url2,
                dataType:'json',
                //data: {id:1001},//也可以是字符串链接"id=1001"，建议用对象
                success: function(data){
                    //create featuresource and featurelayer
                    var jsonSource=new VectorSource({
                    });
                    var features=data.features;
                    for (var i=0;i<features.length;i++)
                    {
                        var feature=features[i];
                        var newfeature=new Feature({
                            geometry:new Point(feature.geometry.coordinates)
                        });
                        newfeature.set("layer",feature.properties.Layer);
                        newfeature.set("text",feature.properties.Text);
                        newfeature.set("vl",i);
                        /*                var a=newfeature.getProperties();
                                        console.log(a);*/
                        jsonSource.addFeature(newfeature);
                    }
                    that.jsonlayer2=new VectorLayer({
                        source:jsonSource,
                        enderMode:'image',
                        style: function (feature) {
                            return styleFunction(feature,4)
                        }

                    });
                    that.map.addLayer(that.jsonlayer2);
                }
            });
            //样式函数
            function styleFunction(feature,type) {
                var text=feature.getProperties().text;
                /*        if(map.getView().getZoom()<20)
                        {
                            height="";
                        }*/
                var color;
                if (type==1)
                {
                    color=" rgba(255,0,255,0.4)";
                    return new Style({
                        image: new CircleStyle({
                            fill: new Fill({
                                color: color
                            }),
                            stroke: new Stroke({
                                color: color,
                                width: 1.25
                            }),
                            radius: 5
                        }),
                        text:new Text({
                            text:text,
                            textAlign:"left",
                            offsetX:7,
                            fill: new Fill({
                                color: color
                            }),
                            stroke:new Stroke({
                                color:color,
                                width:1
                            }),
                            font:" 14px SimHei"
                        })
                    });
                }
                else if (type==2)
                {
                    color=" rgba( 72, 123, 182, 1.00 )";
                    return new Style({
                        image: new RegularShape({
                            fill: new Fill({
                                color: color
                            }),
                            stroke: new Stroke({
                                color: color,
                                width: 1.25
                            }),
                            radius: 7,
                            points:4,
                            angle: Math.PI / 4
                        }),
                        text:new Text({
                            text:text,
                            textAlign:"left",
                            offsetX:7,
                            fill: new Fill({
                                color: color
                            }),
                            stroke:new Stroke({
                                color:color,
                                width:1
                            }),
                            font:" 15px SimHei"
                        })
                    });
                }
                else if (type==3)
                {
                    color=" rgba(255,0,255,0.4)";
                    return new Style({
                        image: new RegularShape({
                            fill: new Fill({
                                color: color
                            }),
                            stroke: new Stroke({
                                color: color,
                                width: 1.25
                            }),
                            radius: 7,
                            points:3,
                            //rotation: Math.PI / 4,
                            //angle:0
                        }),
                        text:new Text({
                            text:text,
                            textAlign:"left",
                            offsetX:7,
                            fill: new Fill({
                                color: color
                            }),
                            stroke:new Stroke({
                                color:color,
                                width:1
                            }),
                            font:" 15px SimHei"
                        })
                    });
                }
                else if (type==4)
                {
                    color=" rgba( 72, 123, 182, 1.00 )";
                    return new Style({
                        image: new Icon({
                            src:"./static/img/icon1.png",
                            //size:[20,20]
                            scale:0.3,
                            rotation: Math.PI / 2
                        }),
                        text:new Text({
                            text:text,
                            textAlign:"left",
                            offsetX:7,
                            fill: new Fill({
                                color: color
                            }),
                            stroke:new Stroke({
                                color:color,
                                width:1
                            }),
                            font:" 15px SimHei"
                        })
                    });
                }

            }
            //添加测量图层
             this.measureSource=new VectorSource();
             this.mmeasureVectorlayer = new VectorLayer({
                source:this.measureSource,
                style: new Style({
                    fill: new Fill({
                        color: 'rgba(255, 255, 255, 0.2)'
                    }),
                    stroke: new Stroke({
                        color: '#ffcc33',
                        width: 2
                    }),
                    image: new CircleStyle({
                        radius: 7,
                        fill: new Fill({
                            color: '#ffcc33'
                        })
                    })
                })
            });
            map.addLayer(this.mmeasureVectorlayer);
            //添加点击事件
            this.selectSingleClick = new Select(
                {
                    layers:function (layer) {
                        if (layer==that.jsonlayer1||layer==that.jsonlayer2)
                        {
                            return true;
                        }
                        else
                        {
                            return false;
                        }
                    }
                }
            );
            this.map.addInteraction(this.selectSingleClick);
            var popup=new Popup(map);
            this.selectSingleClick.on('select', function(e) {
                var features=e.target.getFeatures().getArray();
                if (features.length>0)
                {
                    var feature=features[0];
                    var geometry=feature.getGeometry();
                    var properties=feature.getProperties();
                    if(geometry.getType()=="Point")
                    {
                        popup.show(
                            "基本信息",
                            "图层："+properties.layer+"<br>"+"编号："+properties.text+"<br>"+"数值："+properties.vl+"<br>"+"<button onclick='showDlg()'>查看详细数据</button>",
                            geometry.getCoordinates())
                    }
                }
                else
                {
                    popup.hide()
                }
            });




        },
        /**************************************************************监听*********************************************************************/
        watch:{
            checked1: function (newV,oldV) {
                this.baselayerpoint.setVisible(newV)
                //this.map;
            },
            checked2:function (newV,oldV) {
                this.baselayerpolyline.setVisible(newV);
            },
            checked3:function (newV,oldV) {
                this.baselayerpolygon.setVisible(newV);
            },
            checked4:function (newV,oldV) {
                this.jsonlayer1.setVisible(newV);
            },
            checked5:function (newV,oldV) {
                this.jsonlayer2.setVisible(newV);
            }
        },
        /**************************************************************计算属性*********************************************************************/
        computed: {

        },
        /**************************************************************函数*********************************************************************/
        methods: {
            handleChange(event){
                alert("asdf ")
                alert("asdf ")

                alert("asdf ")

            },
            initData(){
                const today = dtime().format('YYYY-MM-DD')
                Promise.all([userCount(today), orderCount(today), adminDayCount(today), getUserCount(), getOrderCount(), adminCount()])
                    .then(res => {
                        this.userCount = res[0].count;
                        this.orderCount = res[1].count;
                        this.adminCount = res[2].count;
                        this.allUserCount = res[3].count;
                        this.allOrderCount = res[4].count;
                        this.allAdminCount = res[5].count;
                    }).catch(err => {
                    console.log(err)
                })
            },
            getTdtLayer(lyr) {
                var urls=[];
                for(var i=0;i<8;i++)
                {
                    urls.push( "http://t"+i+".tianditu.com/DataServer?T=" + lyr + "&X={x}&Y={y}&L={z}&tk=07c3369864c03fb6a162ac560811db9b")
                }
                var layer = new Tile({
                    source: new XYZ({
                        urls:urls
                    })
                });
                return layer;
            },
            addBaselayers(proname) {
                var that=this;
/*                var map=this.map;
                var baselayerpoint=this.baselayerpoint;
                baselayerpoint=111;
                var baselayerpolyline=this.baselayerpolyline;
                var baselayerpolygon=this.baselayerpolygon;*/
                //点图层
                var urlpoint=proname+"point.geojson";
                $.ajax({
                    type: "GET",
                    url: urlpoint,
                    dataType:'json',
                    //data: {id:1001},//也可以是字符串链接"id=1001"，建议用对象
                    success: function(data){
                        //create featuresource and featurelayer
                        var jsonSource=new VectorSource({
                        });
                        var features=data.features;
                        for (var i=0;i<features.length;i++)
                        {
                            var feature=features[i];
                            var newfeature=new Feature({
                                geometry:new Point(feature.geometry.coordinates)
                            });
                            newfeature.set("layer",feature.properties.Layer);
                            newfeature.set("text",feature.properties.Text);
                            newfeature.set("vl",i);
                            /*                var a=newfeature.getProperties();
                                            console.log(a);*/
                            jsonSource.addFeature(newfeature);
                        }
                        that.baselayerpoint=new VectorLayer({
                            source:jsonSource,
                            style: new Style({
                                image: new CircleStyle({
                                    fill: new Fill({
                                        color: 'rgba( 190, 207, 80, 1.00 )'
                                    }),
                                    stroke: new Stroke({
                                        color: 'rgba( 190, 207, 80, 1.00 )',
                                        width: 1.25
                                    }),
                                    radius: 5
                                })
                            })
                        });
                        that.map.addLayer(that.baselayerpoint);
                    }
                });
                //线图层
                var urlpolyline=proname+"polyline.geojson";
                $.ajax({
                    type: "GET",
                    url: urlpolyline,
                    dataType:'json',
                    //data: {id:1001},//也可以是字符串链接"id=1001"，建议用对象
                    success: function(data){
                        //create featuresource and featurelayer
                        var jsonSource=new VectorSource({
                        });
                        var features=data.features;
                        for (var i=0;i<features.length;i++)
                        {
                            var feature=features[i];
                            var type=feature.geometry.type;
                            if (type=="LineString")
                            {
                                var newfeature=new Feature({
                                    geometry: new LineString(feature.geometry.coordinates)
                                });
                            }
                            else if (type=="MultiLineString")
                            {
                                var newfeature=new Feature({
                                    geometry: new MultiLineString(feature.geometry.coordinates)
                                });
                            }
                            newfeature.set("layer",feature.properties.Layer);
                            newfeature.set("text",feature.properties.Text);
                            newfeature.set("vl",i);
                            /*                var a=newfeature.getProperties();
                                            console.log(a);*/
                            jsonSource.addFeature(newfeature);



                        }
                        that.baselayerpolyline=new VectorLayer({
                            source:jsonSource,
                            style:  new Style({
                                stroke: new Stroke({
                                    color: 'rgba( 183, 72, 75, 1.00 )',
                                    width: 1.25
                                })
                            })
                        });
                        that.map.addLayer(that.baselayerpolyline);
                    }
                });
                //面图层
                var urlpolygon=proname+"polygon.geojson";
                $.ajax({
                    type: "GET",
                    url: urlpolygon,
                    dataType:'json',
                    //data: {id:1001},//也可以是字符串链接"id=1001"，建议用对象
                    success: function(data){
                        //create featuresource and featurelayer
                        var jsonSource=new VectorSource({
                        });
                        var features=data.features;
                        for (var i=0;i<features.length;i++)
                        {
                            var feature=features[i];
                            var newfeature=new Feature({
                                geometry:new Polygon(feature.geometry.coordinates)
                            });
                            newfeature.set("layer",feature.properties.Layer);
                            newfeature.set("text",feature.properties.Text);
                            newfeature.set("vl",i);
                            /*                var a=newfeature.getProperties();
                                            console.log(a);*/
                            jsonSource.addFeature(newfeature);
                        }
                        that.baselayerpolygon=new VectorLayer({
                            source:jsonSource,
                            style:  new Style({
                                fill:new Fill({
                                    color: '#dd942e'
                                })
                            })
                        });
                        that.map.addLayer(that.baselayerpolygon);
                    }
                });
            },
            measuredistance:function () {
                this.measureSource.clear();
                this.map.removeOverlay(this.measureOverlay);
                this.startMeasure("LineString")
                var element= document.getElementById("measure-length")
            },
            measurearea:function () {
                this.measureSource.clear();
                this.map.removeOverlay(this.measureOverlay);
                this.startMeasure("Polygon")

            },
            measurecancel:function () {
                this.measureSource.clear();
                this.map.removeOverlay(this.measureOverlay)
            },
            startMeasure:function (type) {
                var that=this;
                var draw = new Draw({
                    source: that.measureSource,
                    type: type,
                    style: new Style({
                        fill: new Fill({
                            color: 'rgba(255, 255, 255, 0.2)'
                        }),
                        stroke: new Stroke({
                            color: 'rgba(0, 0, 0, 0.5)',
                            lineDash: [10, 10],
                            width: 2
                        }),
                        image: new CircleStyle({
                            radius: 5,
                            stroke: new Stroke({
                                color: 'rgba(0, 0, 0, 0.7)'
                            }),
                            fill: new Fill({
                                color: 'rgba(255, 255, 255, 0.2)'
                            })
                        })
                    }),
                    stopClick:true,
                    freehand:false
                });
                that.map.addInteraction(draw);
                if (that.measureTooltipElement) {
                    that.measureTooltipElement.parentNode.removeChild(measureTooltipElement);
                }
                that.measureTooltipElement = document.createElement('div');
                that.measureTooltipElement.className = 'tooltip tooltip-measure';
                that.measureOverlay = new Overlay({
                    element: that.measureTooltipElement,
                    offset: [0, -15],
                    positioning: 'bottom-center'
                });
                that.map.addOverlay(that.measureOverlay);

                var listener;
                var sketch;
                draw.on('drawstart',
                    function(evt) {
                        //map.removeInteraction(selectSingleClick);

                        // set sketch
                        sketch = evt.feature;

                        /** @type {ol.Coordinate|undefined} */
                        var tooltipCoord = evt.coordinate;

                        listener = sketch.getGeometry().on('change', function(evt) {
                            var geom = evt.target;
                            var output;
                            if (geom instanceof Polygon) {
                                output = that.formatArea(geom);
                                tooltipCoord = geom.getInteriorPoint().getCoordinates();
                            } else if (geom instanceof LineString) {
                                output = that.formatLength(geom);
                                tooltipCoord = geom.getLastCoordinate();
                            }
                            that.measureTooltipElement.innerHTML = output;
                            that.measureOverlay.setPosition(tooltipCoord);
                        });
                    }, this);

                draw.on('drawend',
                    function() {
                        //map.addInteraction(selectSingleClick);

                        that.measureTooltipElement.className = 'tooltip tooltip-static';
                        that.measureOverlay.setOffset([0, -7]);
                        // unset sketch
                        sketch = null;
                        // unset tooltip so that a new one can be created
                        that.measureTooltipElement = null;

                        that.map.removeInteraction(draw);
                    }, this);
            },
            /**
             * Format length output.
             * @param {ol.geom.LineString} line The line.
             * @return {string} The formatted length.
             */
             formatLength: function(line) {
                //var length = ol.Sphere.getLength(line);
                var length = line.getLength();
                var output;
                if (length > 100) {
                    output = (Math.round(length / 1000 * 100) / 100) +
                        ' ' + 'm';
                } else {
                    output = (Math.round(length * 100) / 100) +
                        ' ' + 'mm';
                }
                return output;
            },
            /**
             * Format area output.
             * @param {ol.geom.Polygon} polygon The polygon.
             * @return {string} Formatted area.
             */
            formatArea:function(polygon) {
                var area = getArea(polygon);
                //var area =polygon.getArea();
                var output;
                if (area > 10000) {
                    output = (Math.round(area / 1000000 * 100) / 100) +
                        ' ' + 'm<sup>2</sup>';
                } else {
                    output = (Math.round(area * 100) / 100) +
                        ' ' + 'mm<sup>2</sup>';
                }
                return output;
            },
            handleClose(done) {
                this.$confirm('确认关闭？')
                    .then(_ => {
                        done();
                    })
                    .catch(_ => {});
            },
            showDlg(){
                this.option1 = {
                    title: {
                        text: '沉降量：mm'
                    },
                    tooltip: {
                        trigger: 'axis'
                    },
                    legend: {
                        data:['第三方','施工方']
                    },
                    grid: {
                        left: '3%',
                        right: '4%',
                        bottom: '3%',
                        containLabel: true
                    },
                    toolbox: {
                        feature: {
                            saveAsImage: {}
                        }
                    },
                    xAxis: {
                        type: 'category',
                        boundaryGap: false,
                        data: ['周一','周二','周三','周四','周五','周六','周日']
                    },
                    yAxis: {
                        type: 'value'
                    },
                    series: [
                        {
                            name:'第三方',
                            type:'line',
                            //stack: '总量',
                            data:[2, -2, 5, -5, -1, -5, 2]
                        },
                        {
                            name:'施工方',
                            type:'line',
                            //stack: '总量',
                            data:[1, -1, -5, -6, 1, 5, 3]
                        }
                    ]
                };
                this.option2 = {
                    title: {
                        text: '沉降速率：mm/d'
                    },
                    tooltip: {
                        trigger: 'axis'
                    },
                    legend: {
                        data:['施工方','第三方']
                    },
                    grid: {
                        left: '3%',
                        right: '4%',
                        bottom: '3%',
                        containLabel: true
                    },
                    toolbox: {
                        feature: {
                            saveAsImage: {}
                        }
                    },
                    xAxis: {
                        type: 'category',
                        boundaryGap: false,
                        data: ['周一','周二','周三','周四','周五','周六','周日']
                    },
                    yAxis: {
                        type: 'value'
                    },
                    series: [
                        {
                            name:'第三方',
                            type:'line',
                            stack: '总量',
                            data:[1.1, 0.5, 2.1, 0.2, 0.1, 2.1, 1.5]
                        },
                        {
                            name:'施工方',
                            type:'line',
                            stack: '总量',
                            data:[1.1, 0.5, 2.1, 0.2, 0.1, 2.1, 1.5]
                        }
                    ]
                };
                this.dialogVisible=true;
                setTimeout(() => {
                    ////初始化echarts
                    var myChart = echarts.init(document.getElementById('echarts1'));
                    // 绘制图表
                    myChart.setOption(this.option1);

                    var myChart2 = echarts.init(document.getElementById('echarts2'));
                    // 绘制图表
                    myChart2.setOption(this.option2);

                }, 0)

            },

            //打印事件
            print:function () {
                this.map.once('postcompose', function (event) {
                    var canvas = event.context.canvas;
                    if (navigator.msSaveBlob) {
                        navigator.msSaveBlob(canvas.msToBlob(), 'map.png');
                    } else {
                        canvas.toBlob(function (blob) {
                            saveAs(blob, 'map.png');
                        });
                    }
                });
                this.map.renderSync();
            }


        }
    }
</script>

<style lang="less" >
    #map{
        width: 100%;
        height: 100%;
    }
    #map-measure{
        position: absolute;
        z-index: 10;
        left: 100px;
        top:30px;
    }
    /*测量样式*/
    .tooltip {
        position: relative;
        background: rgba(0, 0, 0, 0.5);
        border-radius: 4px;
        color: white;
        padding: 4px 8px;
        opacity: 0.7;
        white-space: nowrap;
    }
    .tooltip-measure {
        opacity: 1;
        font-weight: bold;
    }
    .tooltip-static {
        background-color: #ffcc33;
        color: black;
        border: 1px solid white;
    }
    .tooltip-measure:before,
    .tooltip-static:before {
        border-top: 6px solid rgba(0, 0, 0, 0.5);
        border-right: 6px solid transparent;
        border-left: 6px solid transparent;
        content: "";
        position: absolute;
        bottom: -6px;
        margin-left: -7px;
        left: 50%;
    }
    .tooltip-static:before {
        border-top-color: #ffcc33;
    }
</style>
